<template>
  <div>
    <el-breadcrumb :separator-icon="ArrowRight" style="padding: 8px">
      <el-breadcrumb-item :to="{path: '/banner/index'}"
        >轮播图列表</el-breadcrumb-item
      >
    </el-breadcrumb>

    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="名字">
        <el-input v-model="queryParams.user" placeholder="请输入名字" />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="queryParams.region" placeholder="请选择分类">
          <el-option label="全部" value="" />
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in categoryList"
            :key="item.id"
          />
          <!-- categoryList -->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>
    <div style="height: 50px; line-height: 50px">
      <el-button type="primary" @click="editHandle">新增</el-button>
    </div>
    <el-table :data="bannerList" style="width: 100%" border>
      <el-table-column label="序号" type="index" align="center" width="80" />
      <el-table-column prop="name" label="图片名称" align="center" />
      <el-table-column prop="link" label="主图" align="center">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.coverImage"
          />
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="描述" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editHandle(scope.row)"
            >修改</el-button
          >
          <el-button type="danger" size="small" @click="delHandle(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 轮播图新增和修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="itemId ? '修改轮播图' : '新增轮播图'"
      width="30%"
    >
      <el-form :model="form" :rules="rules" label-width="70px" ref="formRef">
        <el-form-item label="名字" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="form.category"
            class="m-2"
            placeholder="Select"
            size="large"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in categoryList"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="简介"
          ><el-input v-model="form.desc" type="textarea" />
        </el-form-item>

        <el-form-item label="图片" prop="uploadImg">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:1337/api/v1/common/upload_file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(formRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.pre"
      @pagination="getList"
    />
  </div>
</template>

<script setup>
import {
  getBannerList,
  addBanner,
  putBanner,
  delBanner,
  getIdBanner,
  getBannerCategory,
} from '../../api/banner'
import {ArrowRight} from '@element-plus/icons-vue'
import {reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'

const bannerList = ref([])

let form = reactive({
  category: '',
  name: '',
  link: '',
  url: '',
  desc: '',
  coverImage: '',
})

const total = ref(1)
const formRef = ref()

const rules = reactive({
  name: [{required: true, message: '请输入图片名称', trigger: 'blur'}],
  uploadImg: [
    {
      required: true,
      message: '请上传图片',
      trigger: 'change',
    },
  ],
  category: [
    {
      required: true,
      message: '请选择分类',
      trigger: 'change',
    },
  ],
})
const queryParams = reactive({
  user: '',
  region: '',
  per: 10,
  page: 1,
})
const itemId = ref('')
const dialogVisible = ref(false)
const submitForm = (formEl) => {
  // console.log(formEl);

  if (!formEl) return

  if (itemId.value) {
    formEl.validate(async (valid, fields) => {
      if (valid) {
        const res = await putBanner(form, itemId)
        ElMessage.success('修改成功')
        getList()
      }
    })
  } else {
    formEl.validate(async (valid, fields) => {
      if (valid) {
        const res = await addBanner(form)
        ElMessage.success('添加成功')
        getList()
      }
    })
  }

  dialogVisible.value = false
}

const getList = async () => {
  const res = await getBannerList(queryParams)
  // console.log(res);
  bannerList.value = res.data
  total.value = res?.total
  // console.log(bannerList);
}
getList()

// 删除
const delHandle = (item) => {
  // console.log(item);

  ElMessageBox.confirm('确认要删除吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await delBanner(item.id)
      console.log(res)
      getList()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
// 修改
const editHandle = (item) => {
  dialogVisible.value = true
  itemId.value = item?.id
  console.log(item, 'item')

  if (item.id) {
    getIdBanner(item.id).then((res) => {
      console.log(res)
      Object.keys(form).forEach((v) => {
        form[v] = res[v] || res[v] == 0 ? res[v] : undefined
      })
    })
  }
  // for (let key in form) {
  //   form[key] = item[key] || item[key] == 0 ? item[key] : undefined;
  // }

  console.log(form, 'form')
}

// 重置表单
const resetForm = () => {
  dialogVisible.value = false
}

// 上传逻辑

const handleAvatarSuccess = (response, uploadFile) => {
  // console.log(URL.createObjectURL(uploadFile.raw!));
  // console.log(uploadFile);
  // console.log(URL.createObjectURL(uploadFile.raw!));

  form.coverImage = 'http://localhost:1337' + uploadFile.response?.data
  // console.log(form.coverImage);
}

const beforeAvatarUpload = (rawFile) => {
  // if (rawFile.type !== "image/jpeg") {
  //   ElMessage.error("Avatar picture must be JPG format!");
  //   return false;
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error("Avatar picture size can not exceed 2MB!");
  //   return false;
  // }
  // return true;
}

const onSubmit = () => {
  getList()
}
const categoryList = ref([])
// 获取分类
const getBannerCategoryList = async () => {
  const res = await getBannerCategory()
  console.log(res)
  categoryList.value = res.data
}
getBannerCategoryList()
</script>
<style scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
